package net.csiit.tools.fileserver.core.controller;

import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import net.csiit.tools.fileserver.client.dto.FileInfo;
import net.csiit.tools.fileserver.common.dto.R;
import net.csiit.tools.fileserver.common.util.HttpResponseUtil;
import net.csiit.tools.fileserver.core.entity.FileEntity;
import net.csiit.tools.fileserver.core.storage.FileService;
import net.csiit.tools.fileserver.core.storage.FileStorage;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.StandardMultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.List;

/**
 * //TODO token control
 *
 * @author adam
 * @date 2023-06-09
 */
@RestController
@Slf4j
@RequestMapping("/fileserver")
public class FileController {

    @Autowired
    private FileService fileService;
    @Autowired
    private FileStorage fileStorage;

    @RequestMapping("/getFileInfos")
    public R<List<FileInfo>> getFileInfos(String fileIds) {
        return postFileInfos(Lists.newArrayList(fileIds.split(",")));
    }

    @RequestMapping(value = "/postFileInfos", method = RequestMethod.POST)
    public R<List<FileInfo>> postFileInfos(@RequestBody List<String> fileIds) {
        return R.ok(fileService.getFileInfos(fileIds));
    }

    @RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
    public R<FileInfo> uploadSingleFile(HttpServletRequest request) {
        R<List<FileInfo>> r = uploadFiles(request);
        if (StringUtils.equals(r.getCode(), R.CODE_SUCCESS) && !CollectionUtils.isEmpty(r.getContent())) {
            return R.ok(r.getContent().get(0));
        }

        return R.fail(r.getCode(), r.getMessage());
    }

    @RequestMapping(value = "/uploadFiles", method = RequestMethod.POST)
    public R<List<FileInfo>> uploadFiles(HttpServletRequest request) {
        try {
            if (request instanceof StandardMultipartHttpServletRequest) {
                StandardMultipartHttpServletRequest multipartHttpServletRequest = (StandardMultipartHttpServletRequest) request;
                MultiValueMap<String, MultipartFile> fileMap = multipartHttpServletRequest.getMultiFileMap();
                return fileService.uploadFiles(fileMap);
            }

            return R.fail("500", "未找到文件信息!");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return R.fail("500", "上传失败! " + e.getMessage());
        }
    }

    @RequestMapping("/preview")
    public void previewFile(@RequestParam("fileId") String fileId, HttpServletResponse response) {
        FileEntity entity = fileService.getEntity(fileId);
        if (entity == null) {
            HttpResponseUtil.send404(response);
            return;
        }

        try (InputStream inputStream = fileStorage.readFile(entity.getPath())) {
            HttpResponseUtil.sendFileStream(response, inputStream, entity.getOriginalName());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            try {
                response.sendError(500, "预览失败!");
            } catch (Exception e1) {
                log.error(e1.getMessage(), e1);
            }
        }
    }

}
